﻿using System;
using System.Linq.Expressions;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using netCoreStudy.Auth;
using netCoreStudy.Entities.Base;
using Newtonsoft.Json;

namespace netCoreStudy.Middle
{
	/// <summary>
	/// 老张的异常处理 
	/// </summary>
	public class ErrorHandlingMiddleware
	{
		private readonly RequestDelegate _next;

		public ErrorHandlingMiddleware(RequestDelegate next)
		{
			_next = next;
		}

		public async Task Invoke(HttpContext context)
		{
			// Console.ForegroundColor = ConsoleColor.Red;
			// Console.WriteLine(context.Response.StatusCode);
			try
			{
				await _next(context);
			}
			catch (Exception ex)
			{
				await HandleExceptionAsync(context, ex);
			}
		}

		private static async Task HandleExceptionAsync(HttpContext context, Exception e)
		{
			if (e is UnauthorizedAccessException)
				context.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
			else if (e != null)
				context.Response.StatusCode = (int) HttpStatusCode.BadRequest;

			context.Response.ContentType = "application/json";

			await context.Response
				.WriteAsync(
					JsonConvert.SerializeObject((new ApiResponse(StatusCode.CODE500, e.Message))
						.ResMsg)).ConfigureAwait(false);
		}
	}
}